package com.doge.walknovel.push

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.os.Build
import androidx.core.app.NotificationCompat
import com.bumptech.glide.Glide
import com.doge.wnpro.R
import com.doge.walknovel.business.LauncherActivity
import com.doge.walknovel.core.base.Event.PUSH_INTENT
import com.doge.walknovel.core.base.postEvent
import com.doge.walknovel.utils.*
import com.google.firebase.messaging.RemoteMessage

class PushReceiver : BroadcastReceiver() {
    private var idx = 101

    override fun onReceive(context: Context?, intent: Intent?) {
        // push message received in app
        postEvent(PUSH_INTENT, intent) // do nothing

        log("PushReceiver onReceive $intent")
        notifyPush(intent)
    }

    private fun notifyPush(intent: Intent?) {
        if (intent == null) return
        val title: String? = intent.getStringExtra(FCMService.NOTIFICATION_TITLE)
        val body: String? = intent.getStringExtra(FCMService.NOTIFICATION_BODY)
        val imageUrl: String? = intent.getStringExtra(FCMService.NOTIFICATION_IMAGE_URL)
        val remoteMessage = intent.getParcelableExtra<RemoteMessage?>(FCMService.NOTIFICATION_EXTRA)
        val map: Map<String, String>? = remoteMessage?.data
        requireImage(imageUrl) {
            showNotification(title ?: "", body ?: "", it, map)
        }
    }


    private fun showNotification(
        contentTitle: String,
        contentText: String,
        largeIcon: Bitmap?,
        extraMap: Map<String, String>?
    ) {
        log("Push showNotification [${idx}][${Build.VERSION.SDK_INT}][${Build.VERSION_CODES.O}] contentTitle $contentTitle contentText $contentText ${largeIcon?.byteCount} extraMap $extraMap")
        val channel = "push"
        idx++
        val builder = NotificationCompat.Builder(appContext, channel)
        builder.setSmallIcon(R.mipmap.ic_launcher)
        largeIcon?.let { builder.setLargeIcon(it) }
        builder.setContentTitle(contentTitle)
        builder.setContentText(contentText)
        builder.setSubText("")
        builder.setAutoCancel(true)
        builder.setTicker(contentText)
        builder.priority = NotificationCompat.PRIORITY_DEFAULT
        builder.setWhen(System.currentTimeMillis() + 1000)
        builder.setOngoing(true)
        builder.setDefaults(NotificationCompat.DEFAULT_SOUND)
        val intent = Intent(appContext, LauncherActivity::class.java)
        extraMap?.keys?.forEach {
            intent.putExtra(it, extraMap[it])
        }
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        val pendingIntent = PendingIntent.getActivity(appContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        builder.setContentIntent(pendingIntent)
        val manager =
            appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            manager.createNotificationChannel(
                NotificationChannel(
                    channel, channel,
                    NotificationManager.IMPORTANCE_DEFAULT
                )
            )
        }
        manager.notify(idx, builder.build())
    }

    private fun requireImage(imageUrl: String?, callback: (Bitmap?) -> Unit) {
        log("Push requireImage $imageUrl")
        if (imageUrl.isNullOrEmpty()) {
            callback(null)
        } else {
            runOnIO {
                try {
                    val result: Bitmap? =
                        Glide.with(appContext).asBitmap().load(imageUrl).submit().get()
                    runOnUI { callback(result) }
                } catch (e: Throwable) {
                    callback(null)
                }
            }
        }

    }
}